package fileDemo.excel;

import entity.Person;
import fileDemo.ILoadDataCallback;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.xssf.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SyncFailedException;
import java.util.List;


/**
 * Created by zhangyingjie on 4/29/21
 *
 * @function 第二种写入方式
 */
public class ExcelWriter2 {
    private static final String TAG = "ExcelWriter2";


    //改造分批写入 下文没写，原理：把数据写入多个 excel 。
    public static void writePerssonsToExcelByBatch(List<Person> personList, String path, ILoadDataCallback cb) {
        int mDataCount = personList.size();
        if (mDataCount <= 0) {
            System.err.println("not have data!!!");
            return;
        }

        File file = new File(path);
        if (file.exists()) {
            boolean delete = file.delete();
            System.err.println("delate origin file:"+path+" result:"+delete);
        }

//        String curIndexPath = path + "/record_" + index;
//        String curExcelPath = curIndexPath + "/record.xlsx";
        File curIndexDir = new File(path);
        String parent = curIndexDir.getAbsoluteFile().getParent();
        File parentDir = new File(parent);
        if (!parentDir.exists() || !parentDir.isDirectory()) {
            boolean mkdirs = parentDir.mkdirs();
            System.out.println("mkdirs:" + mkdirs);
        }

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFCellStyle style = workbook.createCellStyle();
        style.setWrapText(true);
        DataFormat format = workbook.createDataFormat();
        style.setDataFormat(format.getFormat("@"));
        XSSFSheet sheet;

        //create sheet
        sheet = workbook.createSheet("sheet0 custom");
        workbook.sheetIterator();

        //header ， 设置 column 宽度
        XSSFRow header = sheet.createRow(0);
        for (int i = 0; i < 5; i++) {
            header.createCell(i).setCellValue(i + "Header: cell data:setWidth: i* 10 * 256:" + i * 10 * 256);
            sheet.setColumnWidth(i, 10 * 256 + i*10*256);
        }

        int mCurrentForProgress = 0;
        for (int i = 0; i < personList.size(); i++) {
            XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);

            Person person = personList.get(i);
            XSSFCell cell = row.createCell(0);
            cell.setCellStyle(style);
            cell.setCellValue("0:"+person.getName());

            row.createCell(1).setCellValue("1:" +person.toString());
            row.createCell(2).setCellValue("2:"+person.toString());
            row.createCell(3).setCellValue("3:"+person.toString());
            row.createCell(4).setCellValue("4:"+person.toString());

            mCurrentForProgress++;
            int progress = (int) (((float) mCurrentForProgress) / mDataCount * 100);
            cb.onProgress(progress);

        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path, false);
            workbook.write(fos);
            fos.flush();
            cb.onResult(1,"success");
//           fos.getFD().sync();//android 正常。
//           java可以捕获到异常。native的，
//            java 如果不强制落盘，也可以读到。、java.io.SyncFailedException: sync failed,
        } catch (SyncFailedException e) {
            System.out.println("SyncFailedException--->");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
